const BaseService = require('./base.service.js')
const ApiResponse = require('../common/api-response.js')
const UserController = require('./user.controller.js')


class WallpaperImageService extends BaseService {
  constructor({cloudObject}) {
    super({ cloudObject }) // 调用父类构造函数
    this.collectionName = 'iss-wallpaper-image'
    this.userController = new UserController(cloudObject)
  }

  // 获取集合引用
  get collection() {
    return this.db.collection(this.collectionName)
  }

  /**
   * 构建JQL简单查询条件
   * @param {Object} query - 查询参数
   * @returns {Object} JQL查询条件
   */
  _buildWhereConditions(query) {
    const whereConditions = {}
  
    if (query.description) {
      whereConditions.description = new RegExp(query.description, 'i')
    }
  
    if (query.classid) {
      if (Array.isArray(query.classid)) {
        whereConditions.classid = {
          $in: query.classid
        }
      } else {
        whereConditions.classid = query.classid
      }
    }
	
	// 增加推荐级别查询条件
	  if (query.recommendLevel) {
	    if (Array.isArray(query.recommendLevel)) {
	      whereConditions.recommendLevel = {
	        $in: query.recommendLevel
	      }
	    } else {
	      whereConditions.recommendLevel = query.recommendLevel
	    }
	  }
  
    if (Array.isArray(query.tabs) && query.tabs.length > 0) {
      whereConditions.tabs = {
        $in: query.tabs
      }
    }
  
    if (query.score) {
      whereConditions.score = query.score
    }
  
    if (query.nickname) {
      whereConditions.nickname = new RegExp(query.nickname, 'i')
    }
  
    if (query.status !== undefined) {
      whereConditions.status = query.status
    }
  
    if (Array.isArray(query.createTime) && query.createTime.length === 2) {
      whereConditions.createTime = {
        $gte: query.createTime[0],
        $lte: query.createTime[1]
      }
    }
  
    if (Array.isArray(query.updateTime) && query.updateTime.length === 2) {
      whereConditions.updateTime = {
        $gte: query.updateTime[0],
        $lte: query.updateTime[1]
      }
    }
  
    return whereConditions
  }

  /**
     * 分页查询壁纸列表
     * @param {Object} query - 查询参数
     * @returns {ApiResponse} 统一响应格式
     */
    async getList(query = {}) {
      try {
		
		// 对权限进行校验
		await this.userController.hasPermission('wir','allin','permission')
		
		this.dbJQL = uniCloud.databaseForJQL()
        const whereConditions = this._buildWhereConditions(query)
        const orderFiled = query.orderFiled || 'updateTime'
        const orderDirection = query.orderDirection || 'desc'
  
		const { total } = await this.collection.where(whereConditions).count()
  
        // 执行查询
        const images = await this.dbJQL.collection(this.collectionName)
          .where(whereConditions)
          .orderBy(orderFiled, orderDirection)
          .skip((query.page - 1) * query.pageSize)
          .limit(query.pageSize)
          .getTemp()
  
        const classifies = this.dbJQL.collection('iss-wallpaper-classify').field('_id, name').getTemp()
		
		const cb = await this.dbJQL.collection(images, classifies).get()
  
        return ApiResponse.success({
          total,
          list: cb.data
        })
      } catch (e) {
        console.error('获取壁纸列表失败:', e)
        return ApiResponse.serverError(ApiResponse.ErrorMessage.SERVICE_ERROR + '-' + e)
      }
    }

  /**
   * 根据id获得对应壁纸
   * @param {string} id - 壁纸ID
   * @returns {ApiResponse} 统一响应格式
   */
  async doc(id) {
    try {
      if (!id) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
      }
      // 对权限进行校验
	  await this.userController.hasPermission('wir','allin','permission')
	  
      const response = await this.collection.doc(id).get()

      if (response.data && response.data.length === 1) {
        return ApiResponse.success(response.data[0])
      }
      return ApiResponse.notFound(ApiResponse.ErrorMessage.IMAGE_NOT_FOUND)
    } catch (e) {
      console.error('获取壁纸失败:', e)
      return ApiResponse.serverError('获取壁纸失败:' + e)
    }
  }

  /**
   * 新增壁纸
   * @param {Object} data - 壁纸数据，【特别注意】：当data.picurl为多张图片时，则会做批量新增
   * @returns {ApiResponse} 统一响应格式
   */
  async add(data) {
    try {
      if (!data || !data.classid || !data.picurl) {
        return ApiResponse.badRequest('分类ID和图片地址不能为空');
      }
  
      // 对权限进行校验
      await this.userController.hasPermission('wia','allin','permission')
	  // 进一步重数据库中获取当前用户的信息
      const userInfoDetail = await this.userController.getUserInfoDBDetal(this.userController.userInfo.uid);
  
      // 准备基础数据
      const baseInsertData = {
        description: (data.description || '').trim(),
        classid: data.classid,
        tabs: Array.isArray(data.tabs) ? data.tabs : [],
        score: data.score || '3.0',
        nickname: (userInfoDetail.nickname || '').trim(),
        status: !!data.status,
        recommendLevel: data.recommendLevel,
        updateTime: Date.now()
      };
  
      // 处理图片URL
      const picUrls = Array.isArray(data.picurl) ? data.picurl : [data.picurl];
  
      // 调用事务云函数
      const result = await uniCloud.callFunction({
        name: 'iss-wallpaper-transaction',
        data: {
          action: 'addWallpapers',
          data: {
            baseData: baseInsertData,
            picUrls: picUrls
          }
        }
      });
  
      if (result.result.success) {
        return ApiResponse.success({
          ids: result.result.ids,
          count: result.result.count
        }, `成功创建${result.result.count}条壁纸记录`);
      } else {
        return ApiResponse.serverError('创建壁纸失败: ' + result.result.error);
      }
    } catch (e) {
      console.error('创建壁纸失败:', e);
      return ApiResponse.serverError('创建壁纸失败: ' + e.message);
    }
  }

  /**
   * 批量删除壁纸
   * @param {Array<string>} ids - 要删除的ID数组
   * @returns {ApiResponse} 统一响应格式
   */
  async remove(ids) {
    try {
      if (!Array.isArray(ids) || ids.length === 0) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.IDS_REQUIRED)
      }
      await this.userController.hasPermission('wid','allin','permission')
	  
      const res = await this.collection.where({_id: this.dbCmd.in(ids)}).get()
      const cloudIds = res.data.map(item=>item.picurl)

      const result = await this.collection.where({
        _id: this.dbCmd.in(ids)
      }).remove()
      
      try{
        // 调用 WallpaperImageService 的 deleteImage 方法删除图片
		if (cloudIds.length > 0) {
			const deleteResult = await this.deleteImage(cloudIds)
			
			if (!deleteResult.success) {
			  console.error('分类图片删除失败:', deleteResult.message)
			  // 这里可以根据需要决定是否继续删除分类数据
			}
		}
      } catch(e) {
        console.log('图片删除失败:' + e)
      }

      if (result.deleted === 0) {
        return ApiResponse.notFound(ApiResponse.ErrorMessage.IMAGE_NOT_FOUND)
      }

      return ApiResponse.success({
        deleted: result.deleted
      }, '删除成功')
    } catch (e) {
      console.error('删除壁纸失败:', e)
      return ApiResponse.serverError('删除壁纸失败:' + e)
    }
  }

  /**
     * 更新壁纸信息
     * @param {Object} data - 包含id和更新数据
     * @returns {ApiResponse} 统一响应格式
     */
    async update(data = {}) {
      try {
        if (!data || !data._id) {
          return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
        }
		
	  // 对权限进行校验
	  await this.userController.hasPermission('wie','allin','permission')
	  // 进一步重数据库中获取当前用户的信息
	  const userInfoDetail = await this.userController.getUserInfoDBDetal(this.userController.userInfo.uid);
        
        // 提取需要更新的数据
        const { _id, updateTime, ...updateData } = data
        
        updateData._uid = userInfoDetail._id
        updateData.nickname = userInfoDetail.nickname
  
        // 执行更新
        const result = await this.collection.where({ _id }).update(updateData)
  
        return ApiResponse.success({
          updated: result.updated
        }, '壁纸更新成功')
      } catch (e) {
        console.error('更新壁纸失败:', e)
        return ApiResponse.serverError('更新壁纸失败: ' + e.message)
      }
    }

  /**
   * 切换bool类型字段状态
   * @param {string} id - 壁纸ID
   * @param {string} fieldName - 字段名
   * @returns {ApiResponse} 统一响应格式
   */
  async columnToggle(id, fieldName) {
    try {
      if (!id) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
      }

      if (!fieldName) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.PARAM_INCOMPLETE)
      }

	  // 对权限进行校验
	  await this.userController.hasPermission('wie','allin','permission')
	  
      // 获取当前状态
      const doc = await this.collection.doc(id).get()
      if (!doc.data || !doc.data.length) {
        return ApiResponse.notFound(ApiResponse.ErrorMessage.IMAGE_NOT_FOUND)
      }

      // 取反状态
      const currentValue = doc.data[0][fieldName]
      const params = { [fieldName]: !currentValue }

      const result = await this.collection.doc(id).update(params)

      if (result.updated === 0) {
        return ApiResponse.notFound('更新失败')
      }

      return ApiResponse.success({
        updated: result.updated
      }, '状态切换成功')
    } catch (e) {
      console.error('切换状态失败:', e)
      return ApiResponse.serverError('切换状态失败:' + e)
    }
  }
  
  /**
   * 根据id删除图片（支持单个ID或ID数组）
   * @param {string|string[]} id - 要删除的图片ID或ID数组
   * @returns {Promise<ApiResponse>} 删除结果
   */
  async deleteImage(id) {
    try {
	  // 对权限进行校验
	  await this.userController.hasPermission(['wid','wie','wcd','wce'],'onein','permission')
      // 统一处理为数组形式
      const ids = Array.isArray(id) ? id : [id];
      
      // 分离七牛云和阿里云的文件ID
      const qiniuFiles = [];
      const aliFiles = [];
      
      ids.forEach(fileId => {
        if (fileId.startsWith('qiniu://')) {
          qiniuFiles.push(fileId);
        } else if (fileId.startsWith('cloud://')) {
          aliFiles.push(fileId);
        } else {
          console.warn('未知文件ID格式，跳过:', fileId);
        }
      });
	  
	  if(qiniuFiles.length > 0) {
		  const extStorageManager = uniCloud.getExtStorageManager({
		    provider: "qiniu",
		    domain: "cdn.isscloud.site",
		  });
		  const res = await extStorageManager.deleteFile({fileList: qiniuFiles});
		  console.log('deleteFile_res',res)
	  }
	  
	  if(aliFiles.length > 0) {
		  const res2 = await uniCloud.deleteFile({fileList: aliFiles})
	  }
    } catch (e) {
      console.error('图片删除失败:', e);
      return ApiResponse.serverError('图片删除失败: ' + e.message);
    }
  }
  
  // 获取所有分类选项
  async getClassifyOptions() {
    try {
      const res = await this.db.collection('iss-wallpaper-classify')
        .where({ enable: true })
        .orderBy('sort', 'asc')
        .get()
      
      return ApiResponse.success(res.data)
    } catch (e) {
      console.error('获取分类选项失败:', e)
      return ApiResponse.serverError('获取分类选项失败:' + e)
    }
  }
}

module.exports = WallpaperImageService